package com.sunny.spring_boot_test.controller;

import com.sunny.spring_boot_test.domain.entity.User;
import com.sunny.spring_boot_test.service.UserService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@RestController
public class HelloWorldController {
    @Resource
    UserService userService;

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, Map<String, Object> map) throws Exception{
        System.out.println("HomeController.login()");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String exception = (String) request.getAttribute("shiroLoginFailure");
        System.out.println("exception=" + exception);
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                System.out.println("UnknownAccountException -- > 账号不存在：");
                msg = "UnknownAccountException -- > 账号不存在：";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                System.out.println("IncorrectCredentialsException -- > 密码不正确：");
                msg = "IncorrectCredentialsException -- > 密码不正确：";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                System.out.println("kaptchaValidateFailed -- > 验证码错误");
                msg = "kaptchaValidateFailed -- > 验证码错误";
            } else {
                msg = "else >> "+exception;
                System.out.println("else -- >" + exception);
            }
        }
        map.put("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("messages", map);
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @GetMapping("/upload")
    public ModelAndView upload(ModelAndView modelAndView) {
        modelAndView.setViewName("files/upload");
        return modelAndView;
    }

    @PostMapping("/upload")
    public ModelAndView singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes, ModelAndView modelAndView) throws IOException {
        modelAndView.setViewName("files/uploadStatus");
        if (file.isEmpty()) {
            modelAndView.addObject("message", "Please select a file to upload");
            return modelAndView;
        }

        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get("C:\\log\\"+ file.getOriginalFilename());
            Files.write(path, bytes);

            modelAndView.addObject("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return modelAndView;
    }

    @RequestMapping("/")
    public String index() {
        return "redirect:/list";
    }

    @RequestMapping("/list")
    public ModelAndView list(ModelAndView modelAndView) {
        List<User> users=userService.getUserList();
        modelAndView.addObject("users", users);
        modelAndView.setViewName("list");
        return modelAndView;
    }

    @RequestMapping("/toAdd")
    public ModelAndView toAdd(ModelAndView modelAndView) {
        modelAndView.setViewName("user/userAdd");
        return modelAndView;
    }

    @RequestMapping("/add")
    public ModelAndView add(User user, ModelAndView modelAndView) {
        userService.save(user);
        modelAndView.setViewName("list");
        return modelAndView;
    }

    @RequestMapping("/toEdit")
    public ModelAndView toEdit(ModelAndView modelAndView,Long id) {
        User user=userService.findUserById(id);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("user/userEdit");
        return modelAndView;
    }

    @RequestMapping("/edit")
    public ModelAndView edit(User user, ModelAndView modelAndView) {
        userService.edit(user);
        modelAndView.setViewName("list");
        return modelAndView;
    }


    @RequestMapping("/delete")
    public ModelAndView delete(Long id, ModelAndView modelAndView) {
        userService.delete(id);
        modelAndView.setViewName("redirect:/list");
        return modelAndView;
    }
}
